package com.kk.controller;

import com.kk.entity.RbacManager;
import com.kk.entity.ResponseEntity;
import com.kk.entity.User;
import com.kk.service.RbacManagerService;
import javafx.application.Application;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.net.BindException;


@Controller
@RequestMapping("/user")
public class MyController  {
    private static ApplicationContext applicationContext;
    static {
        applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    }

    @RequestMapping("/testString")
    public String testString(String name,Model model){
        model.addAttribute("msg",name);
        return "newpage";
    }
    @RequestMapping("/addUser")
    @ResponseBody
    public ResponseEntity addUser(@RequestBody @Valid RbacManager user, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            FieldError fieldError = bindingResult.getFieldError();
            String msg = fieldError.getDefaultMessage();
            return new ResponseEntity(500,msg,null);
        }
        RbacManagerService rbacManagerServiceImpl = applicationContext.getBean("rbacManagerServiceImpl", RbacManagerService.class);
        rbacManagerServiceImpl.addOne(user);
        return new ResponseEntity<>(200,"成功返回",user);
    }

    @RequestMapping("testReturningString")
    public String returnString(@RequestBody String strs,Model model){
        System.out.println(strs);
        model.addAttribute("msg",strs);
        return "success";
    }

    @RequestMapping("testRedirect")
    public String testRedirect(String name){
        return "redirect:/user/testString?name="+name;
    }

    @RequestMapping("testForward")
    public String testForward(String name){
        return "forward:/user/testString?name="+name;
    }
}
